package server

import (
	models "fileshare/controller/modles"
	"fileshare/sqlconn"
	"math/rand"
	"strconv"
	"time"
)

/**
* @program: fileshare
*
* @description: 分享文件的操作
*
* @author: Koco.Allien
*
* @create: 2020-04-11 15:09
**/
//根据file的id获取file信息
func GetFile(fid int) models.BelongInfo {
	file := &models.BelongInfo{}
	sqlconn.MyDB.Model(&models.BelongInfo{}).Where("id = ? ", fid).
		First(file)

	return *file
}

//添加分享数据
func AddSharef(toid, t int, f models.BelongInfo) *models.BelongInfo {
	var ff *models.BelongInfo
	if t == 0 {
		//普通分享
		ff = &models.BelongInfo{
			UpdateAt:   time.Now().Local(),
			CreateAt:   time.Now().Local(),
			FFname:     f.FFname,
			UID:        f.UID,
			UName:      f.UName,
			FPath:      f.FPath,
			Isfolder:   f.Isfolder,
			ToUserid:   toid,
			ToUserName: GetUser(toid).Name,
			Root:       1,
		}
	} else {
		//连接分享
		ff = &models.BelongInfo{
			UpdateAt:   time.Now().Local(),
			CreateAt:   time.Now().Local(),
			FFname:     f.FFname,
			UID:        f.UID,
			UName:      f.UName,
			FPath:      f.FPath,
			Isfolder:   f.Isfolder,
			ToUserid:   toid,
			ToUserName: "urlShare",
			ShareUrl:   f.ShareUrl,
			Code:       f.Code,
			Root:       1,
		}
	}
	sqlconn.MyDB.Create(ff)
	return ff
}

//添加分享链接
func AddShareUrl(f models.BelongInfo) string {

	ff := AddSharef(-1, 1, f)
	ff.ShareUrl = "/download?fid=" + strconv.Itoa(ff.ID)
	rand.Seed(time.Now().Unix())
	ff.Code = time.Now().Format("05") + strconv.Itoa(rand.Intn(100))
	Updatefile(ff)
	return "分享地址信息: http://host地址" + ff.ShareUrl + "       验证码: " + ff.Code
}
